import { defineStore } from 'pinia';
import http from '@/http';
import cache from '@/utils/cache';
import { selfIsland, islandOptions } from '@/config';
import { formatTime, isArray, noteSort, randomID, todoSort } from '@/utils/util';
import { findDataByKey, setDataByKey, updateDataByKey } from '@/utils/indexedDB';
import message from '@/utils/message';

export const useAppStore = defineStore('app', {
    state: () => 
    {
        return {
            islandCurrentData:{} as any,
            islandOptions:{} as any,
            islandStoreData:{} as any,

            appData:[] as any,
            mineBackupAppId:'',
            noteData:[] as any,
            todoData:[] as any,

            dragOutApp:null as any,
            drapOutFlag:false
        };
    },
    getters: {
        getIslandApp: (state) => 
        {
            let arr:any = new Set([]);
            selfIsland.forEach((item) => arr.add(item));
            state.appData.forEach((item) => 
            {
                if (item.children)
                {
                    item.children.forEach((i) => 
                    {
                        if (i.isIsland)
                        {
                            arr.add(i);
                        }
                    });
                }
                if (item.isIsland) 
                {
                    arr.add(item);
                }
            });
            return arr;
        },
        getFolderData: (state) => 
        {
            // 获取文件夹
            let arr = state.appData.filter((item) => 
            {
                if (item.isFolder) 
                {
                    return item;
                }
                return false;
            });
            let arr1 = arr.map((item) => 
            {
                return { value:item.id, label:item.name };
            });
            return arr1;
        },
        getNoteList: (state) => 
        {
            return (sort = 0) => 
            {
                if (!state.noteData.length) return [];
                let newData = [] as any;
                
                newData = state.noteData.map((item) => 
                {
                    let content = item.content;
                    if (item.content.length > 50)
                    {
                        content = item.content.slice(0, 51);
                    }
                    return Object.assign({...item}, { content });
                });
                
                return noteSort(newData, sort);
            };
        },
        getTodoList: (state) => 
        {
            return () => 
            {
                if (!state.todoData.length) return [];
                let newData = [] as any;
                
                newData = state.todoData.map((item) => 
                {
                    let content = item.content;
                    if (item.content.length > 30)
                    {
                        content = item.content.slice(0, 31);
                    }
                    return Object.assign({...item}, { content });
                });
                return todoSort(newData);
            };
        }
    },
    actions: {
        setAppData (flag, data, id)
        {
            this.appData = data;
            this.mineBackupAppId = id;
            if (flag)
            {
                cache.appList.set(JSON.stringify(data));
                cache.mineBackupAppId.set(id);
            }
        },
        setTodoData (flag, data)
        {
            if (!data) return;
            if (isArray(data)) 
            {
                this.todoData = data;
            }
            else
            {
                data.then((res) => 
                {
                    this.todoData = res;
                },
                (err) => 
                {
                    this.todoData = [];
                    message.error('读取数据失败' + err);
                });
            }
            if (flag)
            {
                let newData = this.getTodoList();
                cache.todoList.set(JSON.stringify(newData));
                setDataByKey('todoData', data);
            }
        },
        setNoteData (flag, data)
        {
            if (!data) return;
            if (isArray(data)) 
            {
                this.noteData = data;
            }
            else
            {
                data.then((res) => 
                {
                    this.noteData = res;
                },
                (err) => 
                {
                    this.noteData = [];
                    message.error('读取数据失败' + err);
                });
            }
            if (flag)
            {
                let newData = this.getNoteList(0);
                cache.noteList.set(JSON.stringify(newData));
                setDataByKey('noteData', data);
            }
        },
        async getMyBackupData ()
        {
            if (cache.backupId.get()) 
            {
                // 如果一直在这个页面，重新刷新不重复同步最新数据
                this.setAppData(false, JSON.parse(cache.appList.get()), cache.mineBackupAppId.get());
                this.setTodoData(false, findDataByKey('todoData'));
                this.setNoteData(false, findDataByKey('noteData'));
                return;
            }
            const res = await http.app.getBackupData();
            cache.backupId.set('82y322813jwj191');
            if (!res.data.content.length) 
            {
                this.setAppData(true, [], '');
                this.setTodoData(true, []);
                this.setNoteData(true, []);
                return;
            }
            let data = res.data.content[0];
            this.setAppData(true, data.appList, data.id);
            this.setTodoData(true, data.todo);
            this.setNoteData(true, data.note);
        },
        async backupAllData ()
        {
            await this.backupNoteData();
            await this.backupTodoData();
            await this.backupAppData();
        },
        async backupAppData ()
        {
            // 备份数据到本地和云端
            cache.appList.set(JSON.stringify(this.appData));
            let appList = this.appData.map((item) => 
            {
                if (item.children)
                {
                    let value = item.children.map((i) => i.id);
                    return {
                        name:item.name,
                        isFolder:item.isFolder,
                        children:value,
                        id:item.id
                    };
                }
                return item.id;
            });
            await http.app.backupData({data:appList, backupId:this.mineBackupAppId, type:'appList'}).catch((err) => console.error(err));
            console.log('备份成功');
            
        },
        async backupNoteData ()
        {
            // 备份数据到本地和云端
            let newData = this.getNoteList(0);
            cache.noteList.set(JSON.stringify(newData));
            // 存indexedDB 和 云端
            try
            {
                await updateDataByKey('noteData', this.noteData);
                await http.app.backupData({data:this.noteData, backupId:this.mineBackupAppId, type:'note'});
            }
            catch (err)
            {
                console.error(err);
            }
            
        },
        async backupTodoData ()
        {
            // 备份数据到本地和云端
            let newData = this.getTodoList();
            cache.todoList.set(JSON.stringify(newData));
            // 存indexedDB 和 云端
            try
            {
                await updateDataByKey('todoData', this.todoData);
                await http.app.backupData({data:this.todoData, backupId:this.mineBackupAppId, type:'todo'});
            }
            catch (err)
            {
                console.error(err);
            }
            
        },

        // 备忘录
        addNote (obj)
        {
            this.noteData.unshift(JSON.parse(JSON.stringify(obj)));
        },
        deleteNote (noteId)
        {
            let i1 = this.noteData.findIndex((item) => item.noteId === noteId);  
            this.noteData.splice(i1, 1);
        },
        topNote (noteId)
        {
            let index = this.noteData.findIndex((item) => item.noteId === noteId);
            this.noteData[index].isTop = this.noteData[index].isTop === 0 ? 1 : 0;
            this.noteData[index].ut = formatTime(null);
        },

        // 待办事项
        addTodo (obj)
        {
            this.todoData.unshift(JSON.parse(JSON.stringify(obj)));
        },
        deleteTodo (id)
        {
            let i1 = this.todoData.findIndex((item) => item.todoId === id);  
            this.todoData.splice(i1, 1);
        },
        finishTodo (id)
        {
            let index = this.todoData.findIndex((item) => item.todoId === id);
            this.todoData[index].isFinish = this.todoData[index].isFinish === 0 ? 1 : 0;
            this.todoData[index].ut = formatTime(null);
        },


        // 应用和应用文件夹
        async addApp (data, grouping)
        {
            if (grouping !== '')
            {
                let index = this.appData.findIndex((item) => item.id === grouping);
                this.appData[index].children.push(data);
            }
            else
            {
                this.appData.push(data);
            }
            this.backupAppData();
            await http.app.updateAppData({
                id:data.id,
                inc:1
            });
        },
        async deleteApp (appId)
        {
            let index = this.appData.findIndex((item) => item.id === appId);
            this.appData.splice(index, 1);
            this.backupAppData();
            await http.app.updateAppData({
                id:appId,
                inc:-1
            });
        },
        editFolderName (folderId, newName)
        {
            let index = this.appData.findIndex((item) => item.id === folderId);
            this.appData[index].name = newName;
            this.backupAppData();
        },
        createFolder (name)
        {
            // 创建文件夹
            let obj = {
                id:randomID(6),
                name,
                isFolder:true,
                children:[]  
            };
            this.appData.push(obj);
            this.backupAppData();
        },
        deleteFolder (folderId)
        {
            let data = this.appData.filter((item) => item.id === folderId);
            this.appData = this.appData.concat(data[0].children);
            let index = this.appData.findIndex((item) => item.id === folderId);
            this.appData.splice(index, 1);
            this.backupAppData();
        },

        // 灵动岛
        initIsland ()
        {
            // 初始化灵动岛
            let islandCache = cache.island.get();
            let islandOptionsCache = cache.islandOptions.get();
            if (islandCache && islandOptionsCache)
            {
                let obj = JSON.parse(islandCache);
                let options = JSON.parse(islandOptionsCache);
                this.islandCurrentData = obj;
                this.islandOptions = options;
                return;
            }
            this.setIslandData(selfIsland[0]);
            this.setIslandOptions(islandOptions);
        },
        setIslandData (data)
        {
            this.islandCurrentData = data;
            cache.island.set(JSON.stringify(data));
        },
        setIslandOptions (data)
        {
            this.islandOptions = data;
            cache.islandOptions.set(JSON.stringify(data));
        },
        updateIslandOptions (params, value)
        {
            // 更新灵动岛配置
            if (params === 'borderRadius') value = value + ' !important';
            this.islandOptions[params] = value;
            cache.islandOptions.set(JSON.stringify(this.islandOptions));
        },
        clearIslandOptions ()
        {
            this.setIslandOptions(islandOptions);
        }
    }
});